package com.ukefu.webim.web.handler.apps.sales;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.ukefu.webim.service.repository.*;
import com.ukefu.webim.web.model.*;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snaker.engine.helper.JsonHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.IP;
import com.ukefu.util.Menu;
import com.ukefu.util.PinYinTools;
import com.ukefu.util.UKTools;
import com.ukefu.util.ai.AiUtils;
import com.ukefu.util.asr.AsrResult;
import com.ukefu.util.es.SearchTools;
import com.ukefu.util.es.UKDataBean;
import com.ukefu.util.mobile.MobileAddress;
import com.ukefu.util.mobile.MobileNumberUtils;
import com.ukefu.webim.service.acd.ServiceQuene;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.service.robot.RobotParam;
import com.ukefu.webim.service.robot.RobotReturnParam;
import com.ukefu.webim.util.MessageUtils;
import com.ukefu.webim.util.impl.AiMessageProcesserImpl;
import com.ukefu.webim.util.server.message.ChatMessage;
import com.ukefu.webim.web.handler.Handler;

import love.cq.util.StringUtil;

@Controller
@RequestMapping("/apps/robotsmartivr")
public class RobotSmartIVRController extends Handler {

	@Autowired
	private ExtentionRepository extentionRes;

	@Autowired
	private QueSurveyProcessRepository queSurveryRes;

	@Autowired
	private QueSurveyQuestionRepository queSurveryQuesRes;

	@Autowired
	private QueSurveyAnswerRepository queSurveryAnswerRes;

	@Autowired
	private MetadataRepository metadataRes;

	@Autowired
	private AiMessageProcesserImpl aiMessageProcesser;

	@Autowired
	private QueSurveyResultRepository queSurveyResultRes;

	@Autowired
	private SalesPatterRepository salesPatterRes;

	@Autowired
	private SalesPatterPointRepository salesPatterPointRes;

	@Autowired
	private SalesPatterLevelRepository salesPatterLevelRepository;

	@Autowired
	private QueSurveyResultAnswerRepository queSurveyResultAnswerRes;

	@Autowired
	private QueSurveyResultQuestionRepository queSurveyResultQuestionRes;

	@Autowired
	private QueSurveyResultPointRepository queSurveyResultPointRes;

	@Autowired
	private StatusEventRepository statusEventRes;

	@Autowired
	private StatusEventRobotRepository statusEventRobotRepository;

	private int waittime = 3000;

	@Autowired
	private SalesPatterMediaRepository salesPatterMediaRepository;
	@Autowired
	private MediaRepository mediaRepository;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@RequestMapping({"/asr"})
	@Menu(type = "callout", subtype = "smartivr", access = true)
	@ResponseBody
	public String asr(HttpServletRequest request, @Valid String content, @Valid String action) throws Exception {
		SystemConfig systemConfig = (SystemConfig) CacheHelper.getSystemCacheBean().getCacheObject("systemConfig", UKDataContext.SYSTEM_ORGI);
		if(StringUtils.isNotBlank(content)){
			if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
				this.logger.info("\n接收到来自ROBOT服务器的消息：[{}]",content);
			}
			RobotParam robotParam = UKTools.toObject(content, RobotParam.class);

			if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
				this.logger.info("\n接收到RobotParam对象：[{}]",robotParam.toString());
			}

			if(StringUtils.isNotBlank(action)){
				robotParam.setAction(action);
				if(action.equalsIgnoreCase("reenter") && !StringUtils.isBlank(request.getParameter("text"))) {
					robotParam.setText(request.getParameter("text"));
				}
			}

			RobotReturnParam robotReturnParam = null;
			//机器人分机号 比如：9999
			String ext = robotParam.getUserid();

			List<Extention> extentionList = extentionRes.findByExtention(ext);
			if (extentionList != null && extentionList.size() > 0) {

				//查出对应机器人分机号信息
				Extention extention = extentionList.get(0);

				if (extention != null) {
					//话术 or 智能机器人
					if (!StringUtils.isBlank(extention.getAitype())
							&& extention.getAitype().equals(UKDataContext.AiType.BUSINESSAI.toString())) {
						robotReturnParam = salespatterasr(robotParam,extention);
					}else{
						robotReturnParam = aiasr(robotParam,extention);
					}
				} else {
					//找不到对应机器人
					List<String> voiceList = new ArrayList<>();
					voiceList.add("未配置机器人");
					robotReturnParam = fangyinList(voiceList, null);
				}
			}
			String returnString = JsonHelper.toJson(robotReturnParam);
			if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
				this.logger.info("\n返回给ROBOT服务器的消息：[{}]",returnString);
			}
			return returnString;
		}
		RobotReturnParam robotReturnParam = new RobotReturnParam();
		String returnString = JsonHelper.toJson(robotReturnParam);
		if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
			this.logger.info("\n返回给ROBOT服务器的消息：[{}]",returnString);
		}
		return returnString;
	}

	public RobotReturnParam salespatterasr(RobotParam robotParam,Extention extention) throws Exception {
		UKDataBean dataBean = null;

		//通话记录fs的通话的uuid
		String callid = robotParam.getCdrid().replace("-", "");
		//被叫
		String callerid = robotParam.getTelno();

		//名单ID
		String nameid = robotParam.getTaskid();

		//挂机时 taskid传回来 最后带了 -1？
		if(StringUtils.isNotBlank(robotParam.getParam1()) && "-99".equals(robotParam.getParam1()) && nameid.indexOf("-") > 0){
			nameid = nameid.substring(0,nameid.indexOf("-"));
		}
		RobotReturnParam robotReturnParam = null;

		StatusEvent statusEvent = statusEventRes.findByIdAndOrgi(robotParam.getCdrid(), extention.getOrgi());

		if(StringUtils.isNotBlank(nameid)){
			PageImpl<UKDataBean> dataBeanList = SearchTools.aiidsearch(extention.getOrgi(), nameid);
			if (dataBeanList != null && dataBeanList.getContent().size() > 0) {
				dataBean = dataBeanList.getContent().get(0);
			}
		}else{
			if (statusEvent != null && StringUtils.isNotBlank(statusEvent.getDataid())) {
				PageImpl<UKDataBean> dataBeanList = SearchTools.aiidsearch(extention.getOrgi(), statusEvent.getDataid());
				if (dataBeanList != null && dataBeanList.getContent().size() > 0) {
					dataBean = dataBeanList.getContent().get(0);
				}
			}/* else {
				//TODO 直接用被叫查询 是否有问题？
				PageImpl<UKDataBean> dataBeanList = SearchTools.ainamesearch(extention.getOrgi(), callerid);
				if (dataBeanList != null && dataBeanList.getContent().size() > 0) {
					dataBean = dataBeanList.getContent().get(0);
				}
			}*/
		}
		SystemConfig systemConfig = (SystemConfig) CacheHelper.getSystemCacheBean().getCacheObject("systemConfig", UKDataContext.SYSTEM_ORGI);
		if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
			this.logger.info("\n对应名单数据为：[{}]",dataBean == null?"null 空":UKTools.toJson(dataBean));
		}
		String action = robotParam.getAction();

		//通过action=enter 或aiuser 为空 判断是否第一次进入
		AiUser aiUserFirst = (AiUser) CacheHelper.getOnlineUserCacheBean().getCacheObject(callid,
				extention.getOrgi());

		//开始进入话术
		if ("enter".equals(action) || aiUserFirst == null) {
			AiUser aiUser = this.enterSmartIVR(callerid, callid, extention);
			ChatMessage retMessage = null;
			if (!StringUtils.isBlank(extention.getAitype())
					&& extention.getAitype().equals(UKDataContext.AiType.BUSINESSAI.toString())) {
				aiUser.setAitype(UKDataContext.AiType.BUSINESSAI.toString());
				if (!StringUtils.isBlank(extention.getBustype())
						&& (extention.getBustype().equals(UKDataContext.AiBussType.QUESURVEY.toString())
						|| extention.getBustype().equals(UKDataContext.AiBussType.SALE.toString()))) {
					AiCallOutProcess process = null;
					boolean hangup = false;
					// 话术or问卷
					if (extention.getBustype().equals("sale")) {
						process = salesPatterRes.findByIdAndOrgi(extention.getProid(), extention.getOrgi());
					} else {
						process = queSurveryRes.findByIdAndOrgi(extention.getQueid(), extention.getOrgi());
					}
					aiUser.setBusstype(extention.getBustype());
					if (process != null) {
						// 问卷结果主表
						QueSurveyResult queSurveyResult = new QueSurveyResult();
						queSurveyResult.setProcessid(process.getId());
						queSurveyResult.setEventid(robotParam.getCdrid());
						queSurveyResult.setCreater(aiUser.getUserid());
						queSurveyResult.setCreatetime(new Date());
						queSurveyResult.setOrgi(extention.getOrgi());
						queSurveyResult.setBusstype(extention.getBustype());
						if (statusEvent != null) {
							queSurveyResult.setDiscalled(statusEvent.getDiscalled());
							queSurveyResult.setDistype(statusEvent.getDistype());
						}
						if (dataBean != null) {
							if (dataBean.getActivity() != null) {
								queSurveyResult.setOrgan(dataBean.getActivity().getOrgan());
								queSurveyResult.setActid(dataBean.getActivity().getId());
							}
							if (dataBean.getBatch() != null) {
								queSurveyResult.setBatchid(dataBean.getBatch().getId());
							}
							queSurveyResult.setNameid(dataBean.getId());
						}
						// 问卷结果主表
						queSurveyResultRes.save(queSurveyResult);
						aiUser.setQueresultid(queSurveyResult.getId());

						aiUser.setBussid(process.getId());
						List<VoiceResult> vrList = new ArrayList<>();
						// 查询开始问题节点
						if (StringUtils.isNotBlank(process.getQuestionid())) {
							retMessage = newChatMsg(aiUser,null);

							// 开始节点欢迎语
							QueSurveyQuestion quest = queSurveryQuesRes.findByOrgiAndId(extention.getOrgi(),
									process.getQuestionid());
							if (quest != null) {
								if (!StringUtils.isBlank(quest.getWvtype())
										&& quest.getWvtype().equals("voice")) {
									vrList.add(new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
											null, quest.getQuevoice()));
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
									retMessage.setMessage(quest.getQuevoice());
									retMessage.setMessage(quest.getName());

								} else {
									vrList.add(new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
											quest.getName(), null));
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
									retMessage.setMessage(quest.getName());
								}
								aiUser.setDataid(quest.getId());

								//设置是否允许打断 最大说话时长
								aiUser.setInterrupt(quest.isInterrupt());
								aiUser.setInterrupttime(quest.getInterrupttime() * 1000);
								aiUser.setMaxspreak(quest.getMaxspreak() * 1000);
								aiUser.setLanguage(process.getLanguage());
								//设置 等待超时时长
								aiUser.setLastreplytime(quest.getOvertime() * 1000 );
								aiUser.setDelaytime(process.getDelaytime() * 1000 );

								SysDic sysDic = (SysDic) UKeFuDic.getInstance().get(UKDataContext.UKEFU_SALES_LANG + "." + process.getLanguage() + ".subdiccode");
								if (sysDic != null && StringUtils.isNotBlank(sysDic.getDescription())) {
									aiUser.setLanguagepath(sysDic.getDescription());
								}

								//记录第一个节点
								QueSurveyResultQuestion resultQuestion = null;
								if (resultQuestion == null) {
									//new 一个
									resultQuestion = new QueSurveyResultQuestion();
									resultQuestion.setEventid(aiUser.getUsername());
									resultQuestion.setProcessid(aiUser.getBussid());
									resultQuestion.setQuestionid(aiUser.getDataid());
									resultQuestion.setOrgi(aiUser.getOrgi());
									resultQuestion.setCreatetime(new Date());
								}
								//统计当前问题数据
								resultQuestion.setScore(quest.getScore());
								//resultQuestion.setAnswer(StringUtils.isBlank(resultQuestion.getAnswer()) ? data.getMessage() : resultQuestion.getAnswer() + "," + data.getMessage());
								//resultQuestion.setAnswertimes(resultQuestion.getAnswertimes() + 1);

								// 话术 结束节点 结束通话hangup
								if (2 == quest.getQuetype()) {
									hangup = true;
									aiUser.setBussend(true);
								}
								//转接
								if (3 == quest.getQuetype()) {
									aiUser.setBridge(true);
									aiUser.setTrans(quest.getTrans());
								}
								//记录问题结果
								if (aiUser.isBussend() || aiUser.isBridge()) {
									resultQuestion.setEndtime(new Date());
								}
								resultQuestion = queSurveyResultQuestionRes.save(resultQuestion);
								aiUser.getQuestionList().add(resultQuestion);
							}


						}
						// 欢迎语
						List<String> voices = new ArrayList<>();
						if (!StringUtils.isBlank(process.getWeltype())
								&& process.getWeltype().equals("voice")) {
							vrList.add(0, new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(), null,
									process.getWelvoice()));
							retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
							retMessage.setMessage(process.getWelword() + "," + retMessage.getMessage());
							retMessage.setExpmsg(process.getWelvoice() + "," + retMessage.getMessage());
						} else {
							vrList.add(0, new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
									process.getWelword(), null));
							retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
							retMessage.setMessage(process.getWelword() + "," + retMessage.getMessage());
							retMessage.setExpmsg(process.getWelword() + "," + retMessage.getMessage());
						}
						for (VoiceResult voiceResult : vrList) {
							if (UKDataContext.MediaTypeEnum.TEXT.toString()
									.equals(voiceResult.getVoicetype())) {
								String tts = null;
								if (!StringUtils.isBlank(voiceResult.getTts())) {
									tts = Jsoup.parse(voiceResult.getTts()).text();
									if (tts.length() > 300) {
										tts = tts.substring(0, 300);
									}
									voices.add(processMessage(tts, dataBean));
								}
							} else {
								voices.add(processVoiceURL(voiceResult.getVoice(),extention.getOrgi()));
							}
						}
						if (voices.size() > 0) {
							MessageUtils.createAiMessage(retMessage, retMessage.getAppid(),
									retMessage.getChannel(), UKDataContext.CallTypeEnum.OUT.toString(),
									UKDataContext.AiItemType.AIREPLY.toString(),
									UKDataContext.MediaTypeEnum.TEXT.toString(), retMessage.getUserid());
							if (hangup) {
								// 第一个节点就结束通话
								robotReturnParam = hangUpList(voices, aiUser);
							} else if (aiUser.isBridge()) {
								robotReturnParam = transfer(aiUser.getTrans(), voices, aiUser);
							} else {
								robotReturnParam = defaultplayback(voices, aiUser);
							}
						}
					}
				}
				CacheHelper.getOnlineUserCacheBean().put(aiUser.getSessionid(), aiUser,
						UKDataContext.SYSTEM_ORGI);
			}
		} else {
			String param1 = robotParam.getParam1();

			//挂机
			if("-99".equals(param1)){
				// 电话挂断事件
				AiUser aiUser = (AiUser) CacheHelper.getOnlineUserCacheBean().getCacheObject(callid,
						extention.getOrgi());
				if (aiUser != null) {
					ServiceQuene.processAiService(aiUser, extention.getOrgi(),
							UKDataContext.EndByType.USER.toString());
					AgentUser agentUser = (AgentUser) CacheHelper.getAgentUserCacheBean()
							.getCacheObject(aiUser.getUserid(), UKDataContext.SYSTEM_ORGI);
					if (agentUser != null) {
						ServiceQuene.serviceFinish(agentUser, agentUser.getOrgi(),
								UKDataContext.EndByType.USER.toString(), false);
					}
					this.afterleave(aiUser, extention, dataBean,robotParam);
					//情况缓存数据
					CacheHelper.getOnlineUserCacheBean().delete(aiUser.getSessionid(), UKDataContext.SYSTEM_ORGI);
				}
			}else{
				String message = robotParam.getText();

				String param2 = robotParam.getParam2();
				// 进度流程，按需填写
				if ("timeout".equals(message)) {
					//超时
					AiUser aiUser = (AiUser) CacheHelper.getOnlineUserCacheBean().getCacheObject(callid,
							extention.getOrgi());
					//记录当前问题节点信息
					boolean isadd = false;
					QueSurveyQuestion nextQuestion = null;
					boolean isaddNext = false;
					QueSurveyResultQuestion resultQuestion = aiUser.getQuestionList().size() > 0 ? aiUser.getQuestionList().getLast() : null;
					if (resultQuestion != null && !aiUser.getDataid().equals(resultQuestion.getQuestionid())) {
						isadd = true;
					}
					//问题不存在 或者 问题已经换了
					if (resultQuestion == null || (resultQuestion != null && !aiUser.getDataid().equals(resultQuestion.getQuestionid()))) {
						//new 一个
						resultQuestion = new QueSurveyResultQuestion();
						resultQuestion.setEventid(aiUser.getUsername());
						resultQuestion.setProcessid(aiUser.getBussid());
						resultQuestion.setQuestionid(aiUser.getDataid());
						resultQuestion.setOrgi(aiUser.getOrgi());
						resultQuestion.setCreatetime(new Date());
						isadd = true;
					}
					ChatMessage retMessage = null;
					if (aiUser != null) {
						List<VoiceResult> voiceResultList = new ArrayList<VoiceResult>();
						if (aiUser.isBussend()) {
							robotReturnParam = hangUp();
						} else {
							QueSurveyQuestion currentQues = queSurveryQuesRes.findByOrgiAndId(aiUser.getOrgi(),
									aiUser.getDataid());
							retMessage = newChatMsg(aiUser,null);

							QueSurveyResultAnswer queSurveyResultAnswer = new QueSurveyResultAnswer();
							queSurveyResultAnswer.setAnswertype(UKDataContext.AnswerType.OVERTIME.toString());
							if (currentQues != null && !StringUtils.isBlank(currentQues.getOvertimerepeat())
									&& currentQues.getOvertimerepeat().matches("[0-9]")
									&& aiUser.getTimeoutnums() >= Integer
									.parseInt(currentQues.getOvertimerepeat())) {

								//超时 转接、挂断、 或 跳转其他节点
								if ("trans".equals(currentQues.getOvertimeoperate())) {
									aiUser.setBridge(true);
									aiUser.setTrans(currentQues.getOvertimetrans());
									queSurveyResultAnswer.setAnstatus("trans");
								} else  if ("hangup".equals(currentQues.getOvertimeoperate())) {
									aiUser.setBussend(true);
									queSurveyResultAnswer.setAnstatus("hangup");
									if (!StringUtils.isBlank(currentQues.getOvertimetypeup())
											&& currentQues.getOvertimetypeup().equals("voice")) {
										retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
										retMessage.setMessage(StringUtils.isNotBlank(retMessage.getMessage()) ? retMessage.getMessage() + "," +currentQues.getOvertimewordup():currentQues.getOvertimewordup());
										retMessage.setExpmsg(StringUtils.isNotBlank(retMessage.getExpmsg()) ? retMessage.getExpmsg() + "," + currentQues.getOvertimevoiceup() : currentQues.getOvertimevoiceup());
										voiceResultList
												.add(new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
														null, currentQues.getOvertimevoiceup()));
									} else {
										retMessage.setMessage(StringUtils.isNotBlank(retMessage.getMessage()) ? retMessage.getMessage() + "," +currentQues.getOvertimewordup():currentQues.getOvertimewordup());
										retMessage.setExpmsg(StringUtils.isNotBlank(retMessage.getExpmsg()) ? retMessage.getExpmsg() + "," +currentQues.getOvertimewordup():currentQues.getOvertimewordup());
										voiceResultList
												.add(new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
														currentQues.getOvertimewordup(), null));
										retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
									}
								}else if(StringUtils.isNotBlank(currentQues.getOvertimeoperate())){
									//跳转 下一题
									nextQuestion = queSurveryQuesRes.findByOrgiAndId(currentQues.getOrgi(),currentQues.getOvertimeoperate());

									retMessage = nextQue(aiUser,nextQuestion,voiceResultList);
									isaddNext = true;
									queSurveyResultAnswer.setAnstatus("next");
								}
							} else {
								if (currentQues != null) {
									if (!StringUtils.isBlank(currentQues.getOvertimetype())
											&& currentQues.getOvertimetype().equals("voice")) {
										retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
										retMessage.setMessage(currentQues.getOvertimeword());
										retMessage.setExpmsg(currentQues.getOvertimevoice());
										voiceResultList
												.add(new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
														null, currentQues.getOvertimevoice()));
									} else {
										retMessage.setMessage(currentQues.getOvertimeword());
										retMessage.setExpmsg(currentQues.getOvertimeword());
										voiceResultList
												.add(new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
														currentQues.getOvertimeword(), null));
										retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
									}

									aiUser.setTimeoutnums(aiUser.getTimeoutnums() + 1);
									resultQuestion.setTimeouttimes(aiUser.getTimeoutnums() + 1);
									CacheHelper.getOnlineUserCacheBean().put(aiUser.getSessionid(), aiUser,
											UKDataContext.SYSTEM_ORGI);
								}
								queSurveyResultAnswer.setAnstatus("overtime");
							}

							if ((aiUser.isBussend() || aiUser.isBridge()) && !isaddNext) {
								resultQuestion.setEndtime(new Date());
							}
							//记录问题结果
							if (isadd) {
								resultQuestion = queSurveyResultQuestionRes.save(resultQuestion);
								aiUser.getQuestionList().add(resultQuestion);
							}
							if(isaddNext && nextQuestion != null){
								QueSurveyResultQuestion resultQuestion2 = null;
								//问题不存在 或者 问题已经换了
								if (resultQuestion2 == null) {
									//new 一个
									resultQuestion2 = new QueSurveyResultQuestion();
									resultQuestion2.setEventid(aiUser.getUsername());
									resultQuestion2.setProcessid(aiUser.getBussid());
									resultQuestion2.setQuestionid(aiUser.getDataid());
									resultQuestion2.setOrgi(aiUser.getOrgi());
									resultQuestion2.setCreatetime(new Date());
									resultQuestion2.setScore(nextQuestion.getScore());
								}
								//记录问题结果
								if (aiUser.isBussend() || aiUser.isBridge()) {
									resultQuestion2.setEndtime(new Date());
								}
								resultQuestion2 = queSurveyResultQuestionRes.save(resultQuestion2);
								aiUser.getQuestionList().add(resultQuestion2);
							}

							//记录匹配的答案
							queSurveyResultAnswer.setResultquesid(resultQuestion.getId());
							queSurveyResultAnswer.setProcessid(currentQues.getProcessid());
							queSurveyResultAnswer.setQuestionid(currentQues.getId());
							queSurveyResultAnswer.setAnswerid(UKDataContext.AnswerType.OVERTIME.toString());

							queSurveyResultAnswer.setAnswermsg("");
							queSurveyResultAnswer.setAnswerexpmsg("");

							queSurveyResultAnswer.setAnswerscore(0);
							queSurveyResultAnswer.setCorrect("0");
							queSurveyResultAnswer.setResultid(aiUser.getQueresultid());
							queSurveyResultAnswer.setQuetype(currentQues.getQuetype());
							queSurveyResultAnswer.setOrgi(aiUser.getOrgi());
							queSurveyResultAnswer.setCreater(aiUser.getUserid());
							queSurveyResultAnswer.setCreatetime(new Date());
							queSurveyResultAnswer.setStatuseventid(robotParam.getCdrid());
							queSurveyResultAnswerRes.save(queSurveyResultAnswer);
						}

						if (retMessage != null && !StringUtils.isBlank(retMessage.getMessage())) {
							retMessage.setCreatedate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
							MessageUtils.createAiMessage(retMessage, retMessage.getAppid(),
									retMessage.getChannel(), UKDataContext.CallTypeEnum.OUT.toString(),
									UKDataContext.AiItemType.AIREPLY.toString(),
									UKDataContext.MediaTypeEnum.TEXT.toString(), retMessage.getUserid());

							if (voiceResultList.size() > 0) {
								List<String> voices = new ArrayList<>();
								for (VoiceResult voiceResult : voiceResultList) {
									if (UKDataContext.MediaTypeEnum.TEXT.toString().equals(voiceResult.getVoicetype())) {
										String tts = null;
										if (!StringUtils.isBlank(voiceResult.getTts())) {
											tts = Jsoup.parse(voiceResult.getTts()).text();
											if (tts.length() > 300) {
												tts = tts.substring(0, 300);
											}
											voices.add(processMessage(tts, dataBean));
										}
									} else {
										voices.add(processVoiceURL(voiceResult.getVoice(),extention.getOrgi()));
									}
								}
								if (aiUser.isBussend()) {
									robotReturnParam = hangUpList(voices, aiUser);
								} else if (aiUser.isBridge()) {
									robotReturnParam = transfer(aiUser.getTrans(), voices, aiUser);
								} else {
									robotReturnParam = defaultplayback(voices, aiUser);
								}
							}
						}
						CacheHelper.getOnlineUserCacheBean().put(aiUser.getSessionid(), aiUser, UKDataContext.SYSTEM_ORGI);
					}
					//没有设置超时语 继续asr
					if(robotReturnParam  == null){
						robotReturnParam = noop(true,aiUser);
					}
				}else{
					//TODO
					if(StringUtils.isBlank(param2)){
						//未播放完打断

						AiUser aiUser = (AiUser) CacheHelper.getOnlineUserCacheBean().getCacheObject(callid,extention.getOrgi());
						QueSurveyQuestion currentQues = queSurveryQuesRes.findByOrgiAndId(aiUser.getOrgi(),
								aiUser.getDataid());
						if (currentQues != null && currentQues.isInterrupt() && aiUser!=null && !StringUtils.isBlank(aiUser.getBussid()) && !StringUtils.isBlank(message)) {
							robotReturnParam = asrProcess(robotParam, callid, extention, callerid, dataBean,true);
						}else{
							robotReturnParam = noop(false,aiUser);
						}
					}else{
						robotReturnParam = asrProcess(robotParam, callid, extention, callerid, dataBean,false);
					}

				}
			}
		}
		if(robotReturnParam  == null){
			robotReturnParam = noop(false,null);
		}
		return robotReturnParam;
	}

	/**
	 * 智能机器人asr
	 * @param robotParam
	 * @param extention
	 * @return
	 * @throws Exception
	 */
	public RobotReturnParam aiasr(RobotParam robotParam,Extention extention) throws Exception {


			RobotReturnParam robotReturnParam = null;


			//通话记录fs的通话的uuid
			String callid = robotParam.getCdrid().replace("-", "");
			//被叫
			String callerid = robotParam.getTelno();
			//名单ID
			String nameid = robotParam.getTaskid();


			if (extention != null) {
				UKDataBean dataBean = null;

				StatusEvent statusEvent = statusEventRes.findByIdAndOrgi(robotParam.getCdrid(), extention.getOrgi());
				if(StringUtils.isNotBlank(nameid)){
					PageImpl<UKDataBean> dataBeanList = SearchTools.aiidsearch(extention.getOrgi(), nameid);
					if (dataBeanList != null && dataBeanList.getContent().size() > 0) {
						dataBean = dataBeanList.getContent().get(0);
					}
				}else{
					if (statusEvent != null && StringUtils.isNotBlank(statusEvent.getDataid())) {
						PageImpl<UKDataBean> dataBeanList = SearchTools.aiidsearch(extention.getOrgi(), statusEvent.getDataid());
						if (dataBeanList != null && dataBeanList.getContent().size() > 0) {
							dataBean = dataBeanList.getContent().get(0);
						}
					}
				}
				String action = robotParam.getAction();

				if ("enter".equals(action)) {
					AiUser aiUser = this.enterSmartIVR(callerid, callid, extention);
					ChatMessage retMessage = null;
						//智能机器人
					AiConfig aiConfig = AiUtils.initAiConfig(extention.getAiid(), extention.getOrgi());
					aiUser.setAitype(UKDataContext.AiType.SMARTAI.toString());
					aiUser.setLanguage(extention.getLanguage());
					aiUser.setLastreplytime(extention.getWaittime());
					SysDic sysDic = (SysDic) UKeFuDic.getInstance().get(UKDataContext.UKEFU_SALES_LANG + "." + extention.getLanguage() + ".subdiccode");
					if (sysDic != null && StringUtils.isNotBlank(sysDic.getDescription())) {
						aiUser.setLanguagepath(sysDic.getDescription());
					}
					if (aiConfig != null) {
						List<String> voices = new ArrayList<>();
						String me = processMessage(extention.getWelcomemsg(), dataBean);
						voices.add(me);
						retMessage = newChatMsg(aiUser,null);

						retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
						retMessage.setMessage(me);
						retMessage.setExpmsg(me);
						MessageUtils.createAiMessage(retMessage, retMessage.getAppid(),
								retMessage.getChannel(), UKDataContext.CallTypeEnum.OUT.toString(),
								UKDataContext.AiItemType.AIREPLY.toString(),
								UKDataContext.MediaTypeEnum.TEXT.toString(), retMessage.getUserid());

						robotReturnParam = defaultplayback(voices, aiUser);
					} else if (extention != null && !StringUtils.isBlank(extention.getErrormessage())) {
						List<String> voiceList = new ArrayList<>();
						voiceList.add(processMessage(extention.getErrormessage(), dataBean));
						robotReturnParam = fangyinList(voiceList, null);
					} else {
						//fangyin("未配置机器人", aiUser);
						//找不到对应机器人
						List<String> voiceList = new ArrayList<>();
						voiceList.add("未配置机器人");
						robotReturnParam = fangyinList(voiceList, null);
					}
				}else {
					String param1 = robotParam.getParam1();
					//挂机
					if("-99".equals(param1)){
						// 电话挂断事件
						AiUser aiUser = (AiUser) CacheHelper.getOnlineUserCacheBean().getCacheObject(callid,
								extention.getOrgi());
						if (aiUser != null) {
							ServiceQuene.processAiService(aiUser, extention.getOrgi(),
									UKDataContext.EndByType.USER.toString());
							AgentUser agentUser = (AgentUser) CacheHelper.getAgentUserCacheBean()
									.getCacheObject(aiUser.getUserid(), UKDataContext.SYSTEM_ORGI);
							if (agentUser != null) {
								ServiceQuene.serviceFinish(agentUser, agentUser.getOrgi(),
										UKDataContext.EndByType.USER.toString(), false);
							}
							//智能机器人 返回hungup给外部机器人
							ChatMessage data = newChatMsg(aiUser,null);
							data.setAiid(extention.getAiid());
							data.setBustype(UKDataContext.MediaTypeEnum.HUNGUP.toString());
							data.setMessage(UKDataContext.MediaTypeEnum.HUNGUP.toString());
							aiMessageProcesser.chat(data);

							//情况缓存数据
							CacheHelper.getOnlineUserCacheBean().delete(aiUser.getSessionid(), UKDataContext.SYSTEM_ORGI);
						}
					}else{
						String message = robotParam.getText();
						// 进度流程，按需填写
						if ("timeout".equals(message)) {
							//超时
							AiUser aiUser = (AiUser) CacheHelper.getOnlineUserCacheBean().getCacheObject(callid,
									extention.getOrgi());
							ChatMessage retMessage = null;
							if (aiUser != null) {
								if (aiUser.isBussend()) {
									robotReturnParam = hangUp();
								} else {
										//智能机器人 返回hungup给外部机器人
										retMessage = newChatMsg(aiUser,null);
										retMessage.setAiid(extention.getAiid());

										//机器人重复提示音
										if (extention.getWaittiptimes() > 0 && aiUser.getRetimes() < extention.getWaittiptimes()) {
											if (!StringUtils.isBlank(extention.getWaitmsg())) {
												String[] msgList = extention.getWaitmsg().split("[;；]");
												if (msgList.length > aiUser.getRetimes()) {
													retMessage.setMessage(msgList[aiUser.getRetimes()]);
													retMessage.setExpmsg(msgList[aiUser.getRetimes()]);
													retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
												} else {
													retMessage.setMessage(msgList[msgList.length - 1]);
													retMessage.setExpmsg(msgList[msgList.length - 1]);
													retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
												}
											} else {
												retMessage.setMessage("您好，您还在吗？");
												retMessage.setExpmsg("您好，您还在吗？");
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
											}
											aiUser.setRetimes(aiUser.getRetimes() + 1);
											CacheHelper.getOnlineUserCacheBean().put(aiUser.getSessionid(), aiUser,
													UKDataContext.SYSTEM_ORGI);
										} else {
											retMessage.setBustype(UKDataContext.MediaTypeEnum.HUNGUP.toString());
											retMessage.setMessage(!StringUtils.isBlank(extention.getErrormessage()) ? extention.getErrormessage() : "再见");
											retMessage.setExpmsg(!StringUtils.isBlank(extention.getErrormessage()) ? extention.getErrormessage() : "再见");
											retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
										}
//									}
								}

								if (retMessage != null && !StringUtils.isBlank(retMessage.getMessage())) {
									retMessage.setCreatedate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
									MessageUtils.createAiMessage(retMessage, retMessage.getAppid(),
											retMessage.getChannel(), UKDataContext.CallTypeEnum.OUT.toString(),
											UKDataContext.AiItemType.AIREPLY.toString(),
											UKDataContext.MediaTypeEnum.TEXT.toString(), retMessage.getUserid());
									//智能机器人
									String retText = retMessage != null && !StringUtils.isBlank(retMessage.getMessage())
											? retMessage.getMessage()
											: extention.getTipmessage();
									if (!StringUtils.isBlank(retText)) {
										List<String> voices = new ArrayList<>();
										if (UKDataContext.MediaTypeEnum.TEXT.toString().equals(retMessage.getMsgtype())) {
											String tts = null;
											if (!StringUtils.isBlank(retMessage.getMessage())) {
												tts = Jsoup.parse(retMessage.getMessage()).text();
												if (tts.length() > 300) {
													tts = tts.substring(0, 300);
												}
												voices.add(processMessage(tts,dataBean));
											}
										} else {
											voices.add(retMessage.getMessage());
										}
										if (voices.size() > 0) {
											//外部机器人挂断
											if (UKDataContext.MediaTypeEnum.HUNGUP.toString().equalsIgnoreCase(retMessage.getBustype())) {
												robotReturnParam = hangUpList(voices, aiUser);
											} else if (UKDataContext.MediaTypeEnum.TRANS.toString().equalsIgnoreCase(retMessage.getBustype())) {
												//转接
												//map = beforeTransfer(retMessage.getCode(), voices, aiUser);
												robotReturnParam = transfer(retMessage.getCode(), voices, aiUser);
											} else {
												//map = fangyinList(voices, aiUser);
												robotReturnParam = defaultplayback(voices, aiUser);
											}
										}
									}
								}
								CacheHelper.getOnlineUserCacheBean().put(aiUser.getSessionid(), aiUser, UKDataContext.SYSTEM_ORGI);
							}
							//没有设置超时语 继续asr
							if(robotReturnParam  == null){
								robotReturnParam = noop(true,aiUser);
							}
						}else{
							if ("reenter".equals(action)) {
								AiUser aiUser = this.enterSmartIVR(callerid, callid, extention);
								CacheHelper.getOnlineUserCacheBean().put(aiUser.getSessionid(), aiUser, UKDataContext.SYSTEM_ORGI);
							}
							//智能机器人
							robotReturnParam = aiasrProcess(robotParam, callid, extention, callerid, dataBean);
						}
					}

				}
			return robotReturnParam;
		}
		robotReturnParam = new RobotReturnParam();
		return robotReturnParam;
	}


	/**
	 *
	 * @param voice
	 * @return
	 */
	private String processVoiceURL(String voice,String orgi) {
		if (StringUtils.isBlank(voice)) {
			return null;
		}
		SystemConfig systemConfig = UKTools.getSystemConfig();
		String host = systemConfig.getIconstr();
		if (!StringUtils.isBlank(host)) {

			Media media = mediaRepository.findByIdAndOrgi(voice,orgi);
			String filename = "";
			if(media != null){
				filename = media.getFilename();
			}
			if(StringUtils.isBlank(filename)){
				SalesPatterMedia sptMedia = salesPatterMediaRepository.findByIdAndOrgi(voice,orgi);
				if (sptMedia != null) {
					filename = sptMedia.getFilename() ;
				}
			}
			if(StringUtils.isBlank(filename)){
				filename = "media/" + voice + ".mp3";
			}
			host = host + "/res/voice/" + filename;
            //url
			host = "U:" + host;
		}
		return host;
	}

	/**
	 * 组装文本
	 * @param message
	 * @param dataBean
	 * @return
	 */
	private String processMessage(String message, UKDataBean dataBean) {
		/**
		 * 找名单数据，替换内容参数
		 */
		Object value = null;
		SystemConfig systemConfig = (SystemConfig) CacheHelper.getSystemCacheBean().getCacheObject("systemConfig", UKDataContext.SYSTEM_ORGI);
		if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
			this.logger.info("\n替换参数，对应名单数据为：[{}]",dataBean == null?"null 空":UKTools.toJson(dataBean));
		}
		if (dataBean != null && dataBean.getValues() != null) {
			MetadataTable table = metadataRes.findByTablenameIgnoreCase(dataBean.getType());
			if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
				this.logger.info("\n替换参数，对应名单的数据结构为：[{}]",table == null?"null 空":UKTools.toJson(table));
			}
			if (table != null) {
				Map<String, Object> values = new HashMap<String, Object>();
				for (TableProperties tp : table.getTableproperty()) {
					values.put(tp.getName(), dataBean.getValues().get(tp.getFieldname()));
					values.put(tp.getFieldname(), dataBean.getValues().get(tp.getFieldname()));
				}
				Pattern pattern = Pattern.compile("\\[([\\S\\s]*?)\\]");
				Matcher matcher = pattern.matcher(message);
				StringBuffer strb = new StringBuffer();
				while (matcher.find()) {
					if (!StringUtils.isBlank(matcher.group(1)) && values.get(matcher.group(1)) != null) {
						matcher.appendReplacement(strb, values.get(matcher.group(1)).toString());
					} else {
						matcher.appendReplacement(strb, "");
					}
				}
				matcher.appendTail(strb);
				message = strb.toString();
				if(systemConfig!=null && "debug".equals(systemConfig.getLoglevel())){
					this.logger.info("\n替换参数后语句为：[{}]",message == null?"null 空":message);
				}
			}
		}
		message = value != null ? value.toString() : message;
		//文字前要以 T：
		return "T:" + message;
	}

	/**
	 * 进入IVR
	 * @param callerid
	 * @param callid
	 * @param extention
	 * @return
	 * @throws Exception
	 */
	private AiUser enterSmartIVR(String callerid, String callid, Extention extention)
			throws Exception {
		MobileAddress address = MobileNumberUtils.getAddress(callerid);

		AiUser aiUser = new AiUser(callid, callid, System.currentTimeMillis(), extention.getOrgi(), new IP());
		aiUser.setContextid(callid);
		if (address != null) {
			aiUser.getIpdata().setCountry(address.getCountry());
			aiUser.getIpdata().setProvince(address.getProvince());
			aiUser.getIpdata().setCity(address.getCity());
			aiUser.getIpdata().setRegion(address.getProvince() + address.getCity() + address.getIsp());
		} else {
			aiUser.getIpdata().setRegion("内线");
		}
		aiUser.setCallnumber(extention.getExtention());
		aiUser.setSessionid(aiUser.getId());
		aiUser.setAppid(extention.getHostid());
		aiUser.setAiid(extention.getAiid());
		aiUser.setUsername(callerid);

		aiUser.setChannel(UKDataContext.ChannelTypeEnum.PHONE.toString());

		AgentService agentService = ServiceQuene.processAiService(aiUser, extention.getOrgi(), null);
		aiUser.setAgentserviceid(agentService.getId());

		//放入缓存
		CacheHelper.getOnlineUserCacheBean().put(aiUser.getSessionid(), aiUser, UKDataContext.SYSTEM_ORGI);

		aiUser.setEos_eng(extention.getEoseng());
		aiUser.setSos_eng(extention.getSoseng());
		aiUser.setEos_time(extention.getEostime());
		return aiUser;
	}

	/**
	 * 匹配不中结果 继续放音
	 * @param isNewAsr 是否新一段asr 还是继续播放旧的录音
	 * @return
	 */
	private RobotReturnParam noop(boolean isNewAsr,AiUser aiUser) {
		RobotReturnParam robotReturnParam = new RobotReturnParam(aiUser);
		if(isNewAsr){
			robotReturnParam.setAsrvoice("m00.wav");
		}
		robotReturnParam.setParam2("-9");
		return robotReturnParam;
	}

	/**
	 * 话术 处理asr结果
	 * @param robotParam
	 * @param callid
	 * @param extention
	 * @param callerid
	 * @param dataBean
	 * @return
	 * @throws JSONException
	 */
	public RobotReturnParam asrProcess(RobotParam robotParam, String callid, Extention extention, String callerid,
										  UKDataBean dataBean,boolean isInterrupt) throws JSONException {
		AiUser aiUser = (AiUser) CacheHelper.getOnlineUserCacheBean().getCacheObject(callid, extention.getOrgi());
		RobotReturnParam robotReturnParam = null;
		if (aiUser != null && aiUser.isBussend() == false) {
			ChatMessage data = newChatMsg(aiUser,null);
			//TODO 返回 客户说话时长
			/*AsrResult asrResult = UKTools.parseAsrResult(robotParam.getCdrid(), robotParam.getText(),
					0);*/
			AsrResult asrResult = new AsrResult(robotParam.getCdrid(), robotParam.getText(),"0");

			if(StringUtils.isNotBlank(robotParam.getWavfile())){
				asrResult.setRecordpath(robotParam.getWavfile());
			}
			data.setAiid(extention.getAiid());
			if (asrResult != null && !StringUtils.isBlank(asrResult.getMessage())) {
				asrResult.setMessage(asrResult.getMessage().replaceAll("[\\p{P}+~$`^=|<>～｀＄＾＋＝｜＜＞￥×]", ""));
				if (asrResult.getMessage().endsWith("。")) {
					data.setMessage(asrResult.getMessage().substring(0, asrResult.getMessage().length() - 1));
				} else {
					data.setMessage(asrResult.getMessage());
				}
				data.setDuration((int) Math.ceil(asrResult.getSpeakms() / 1000f));
				data.setExpmsg(asrResult.getMessage());
				List<VoiceResult> voiceResultList = new ArrayList<VoiceResult>();

				//TODO 确认录音地址
				if (!StringUtil.isBlank(data.getMessage())) {
					data.setUrl("/apps/resource/asr/" + asrResult.getRecordpath());
				}
				data.setMediaid(robotParam.getCdrid());

				/**
				 * 输入消息
				 */
				MessageUtils.createAiMessage(data, data.getAppid(), UKDataContext.ChannelTypeEnum.PHONE.toString(),
						UKDataContext.CallTypeEnum.IN.toString(), UKDataContext.AiItemType.USERINPUT.toString(),
						UKDataContext.MediaTypeEnum.TEXT.toString(), data.getUserid());
				/**
				 * 使用 ASR识别结果作为消息内容
				 */
				data.setMessage(data.getExpmsg());

				ChatMessage retMessage = null;
					if (!StringUtils.isBlank(aiUser.getBusstype())
							&& (aiUser.getBusstype().equals(UKDataContext.AiBussType.QUESURVEY.toString())
							|| aiUser.getBusstype().equals(UKDataContext.AiBussType.SALE.toString()))
							&& !StringUtils.isBlank(aiUser.getDataid())) {
						//公共方法，从缓存中获取（提升性能）
						List<QueSurveyAnswer> ansList = loadAnswer(aiUser.getDataid(), extention.getOrgi()) ;
						QueSurveyQuestion currentQues = queSurveryQuesRes.findByOrgiAndId(aiUser.getOrgi(),
								aiUser.getDataid());
						//公共答案（公共方法，方便从缓存中获取）
						List<QueSurveyAnswer> publicAnsList = loadPubAnswer(currentQues.getProcessid(), extention.getOrgi(),false) ;
						List<QueSurveyAnswer> publicAnsInterruptList = loadPubAnswer(currentQues.getProcessid(), extention.getOrgi(),true) ;

						QueSurveyResult queSurveyResult = queSurveyResultRes.findByIdAndOrgi(aiUser.getQueresultid(),
								aiUser.getOrgi());
						//记录当前问题节点信息
						boolean isadd = false;
						QueSurveyResultQuestion resultQuestion = aiUser.getQuestionList().size() > 0 ? aiUser.getQuestionList().getLast() : null;
						if (resultQuestion != null && !resultQuestion.getQuestionid().equals(currentQues.getId())) {
							resultQuestion.setEndtime(new Date());
							isadd = true;
						}
						//问题不存在 或者 问题已经换了
						if (resultQuestion == null || (resultQuestion != null && !resultQuestion.getQuestionid().equals(currentQues.getId()))) {
							//new 一个
							resultQuestion = new QueSurveyResultQuestion();
							resultQuestion.setEventid(aiUser.getUsername());
							resultQuestion.setProcessid(aiUser.getBussid());
							resultQuestion.setQuestionid(aiUser.getDataid());
							resultQuestion.setOrgi(aiUser.getOrgi());
							resultQuestion.setCreatetime(new Date());
							isadd = true;

						}
						//统计当前问题数据
						resultQuestion.setScore(currentQues.getScore());
						resultQuestion.setAnswer(StringUtils.isBlank(resultQuestion.getAnswer()) ? data.getMessage() : resultQuestion.getAnswer() + "," + data.getMessage());
						resultQuestion.setAnswertimes(resultQuestion.getAnswertimes() + 1);
						//匹配答案
						int ansnum = 0;// 问答次数
						boolean ismatch = false;

						boolean isrepeat = false;//重复
						QueSurveyAnswer ans = null;

						QueSurveyResultAnswer queSurveyResultAnswer = new QueSurveyResultAnswer();
						//优先匹配允许打断的公共词库
						if (!ismatch) {
							if (publicAnsInterruptList != null && publicAnsInterruptList.size() > 0) {
								for (QueSurveyAnswer ansobj : publicAnsInterruptList) {
									if (matchKeyWord(ansobj.getAnswer(), data.getMessage(), false,queSurveyResultAnswer)) {
										ans = ansobj;
										ismatch = true;
										break;
									}
								}
							}

						}
						//优先匹配允许打断的公共词库
						if (!ismatch) {
							if (publicAnsInterruptList != null && publicAnsInterruptList.size() > 0) {
								for (QueSurveyAnswer ansobj : publicAnsInterruptList) {
									if (matchKeyWord(ansobj.getAnswer(), data.getMessage(), true,queSurveyResultAnswer)) {
										ans = ansobj;
										ismatch = true;
										break;
									}
								}
							}

						}
						//非indexof查找一遍
						if (!ismatch) {
							for (QueSurveyAnswer ansobj : ansList) {
								ansnum = ansnum + 1;
								if (matchKeyWord(ansobj.getAnswer(), data.getMessage(), false,queSurveyResultAnswer)) {
									ans = ansobj;
									ismatch = true;
									break;
								}
							}
						}
						//indexof查找一遍
						if (!ismatch) {
							for (QueSurveyAnswer ansobj : ansList) {
								ansnum = ansnum + 1;
								if (matchKeyWord(ansobj.getAnswer(), data.getMessage(), true,queSurveyResultAnswer)) {
									ans = ansobj;
									ismatch = true;
									break;
								}
							}
						}
						//打断模式下 以下不匹配
						if(!isInterrupt){
							//设置的答案 不匹配就先寻找匹配重复语
							if (!ismatch) {
								if (!StringUtils.isBlank(currentQues.getReplykeyword())
										&& matchKeyWord(currentQues.getReplykeyword(), asrResult.getMessage(), false,queSurveyResultAnswer)) {
									ismatch = true;
									isrepeat = true;
								}
							}
							//设置的答案 不匹配就先寻找匹配重复语
							if (!ismatch) {
								if (!StringUtils.isBlank(currentQues.getReplykeyword())
										&& matchKeyWord(currentQues.getReplykeyword(), asrResult.getMessage(), true,queSurveyResultAnswer)) {
									ismatch = true;
									isrepeat = true;
								}
							}
							//不匹配再找公共词库
							if (!ismatch) {
								if (publicAnsList != null && publicAnsList.size() > 0) {
									for (QueSurveyAnswer ansobj : publicAnsList) {
										if (matchKeyWord(ansobj.getAnswer(), data.getMessage(), false,queSurveyResultAnswer)) {
											ans = ansobj;
											ismatch = true;
											break;
										}
									}
								}

							}
							//不匹配再找公共词库
							if (!ismatch) {
								if (publicAnsList != null && publicAnsList.size() > 0) {
									for (QueSurveyAnswer ansobj : publicAnsList) {
										if (matchKeyWord(ansobj.getAnswer(), data.getMessage(), true,queSurveyResultAnswer)) {
											ans = ansobj;
											ismatch = true;
											break;
										}
									}
								}

							}
						}

						if (!ismatch) {
							for (QueSurveyAnswer ansobj : ansList) {
								//未识别 目前答案为空
								if (StringUtils.isBlank(ansobj.getAnswer())) {
									ans = ansobj;
								}
							}
						}
						//设置回答错误
						boolean isError = false;
						if(!isInterrupt){
							if(!StringUtils.isBlank(currentQues.getErrortype()) && !StringUtils.isBlank(currentQues.getErrorepeat()) &&
									!StringUtils.isBlank(currentQues.getErroroperate())){
								isError = true;
							}
						}

						queSurveyResultAnswer.setResultid(queSurveyResult.getId());

						QueSurveyQuestion nextQuestion = null;
						Boolean isAddNext = false;
								//下一题
						QueSurveyQuestion question = ans != null ? queSurveryQuesRes.findByOrgiAndId(ans.getOrgi(),
								ans.getQueid()) : null;
						//下一题为结束（hangup） 或 下一题存在
						if (ans != null && !StringUtils.isBlank(ans.getQueid()) && ((ans.getQueid().equals("hangup")) || (ans.getQueid().equals("currentnode")) || ((!ans.getQueid().equals("hangup")) && (!ans.getQueid().equals("currentnode")) && question != null))) {
							if (ans.getQueid().equals("hangup")) {// 结束
								aiUser.setDataid(ans.getId());
								retMessage = newChatMsg(aiUser,null);
								if (!StringUtils.isBlank(ans.getHanguptype())
										&& ans.getHanguptype().equals("voice")) {
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
									retMessage.setExpmsg(ans.getHangupvoice());
									retMessage.setMessage(StringUtils.isNotBlank(ans.getHangupmsg())?ans.getHangupmsg():ans.getHangupvoice());
									voiceResultList
											.add(new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
													null, ans.getHangupvoice()));
								} else {
									retMessage.setMessage(ans.getHangupmsg());
									retMessage.setExpmsg(ans.getHangupmsg());
									voiceResultList
											.add(new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
													ans.getHangupmsg(), null));
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
								}
                                aiUser.setBussend(true);

								queSurveyResultAnswer.setAnstatus("end");// 结束

							} else if (ans.getQueid().equals("currentnode")) {//继续当前节点

								isAddNext = true;
								nextQuestion = question;

								aiUser.setDataid(currentQues.getId());
								//设置是否允许打断 最大说话时长
								aiUser.setInterrupt(currentQues.isInterrupt());
								aiUser.setInterrupttime(currentQues.getInterrupttime() * 1000);
								aiUser.setMaxspreak(currentQues.getMaxspreak() * 1000);
								//设置 等待超时时长
								aiUser.setLastreplytime(currentQues.getOvertime() * 1000);
								aiUser.setBridge(false);

								retMessage = newChatMsg(aiUser,null);
								//播放当前匹配到的答案的 提示语
								if (!StringUtils.isBlank(ans.getHanguptype())
										&& ans.getHanguptype().equals("voice")) {
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
									retMessage.setMessage(StringUtils.isNotBlank(ans.getHangupmsg())?ans.getHangupmsg():ans.getHangupvoice());
									retMessage.setExpmsg(ans.getHangupvoice());
									voiceResultList
											.add(new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
													null, ans.getHangupvoice()));
								} else if (StringUtils.isNotBlank(ans.getHangupmsg())) {
									retMessage.setMessage(ans.getHangupmsg());
									retMessage.setExpmsg(ans.getHangupmsg());
									voiceResultList
											.add(new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
													ans.getHangupmsg(), null));
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
									retMessage.setMessage(ans.getHangupmsg());
								} else {
									if (!StringUtils.isBlank(currentQues.getWvtype())
											&& currentQues.getWvtype().equals("voice")) {
										retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
										retMessage.setExpmsg(currentQues.getQuevoice());
										retMessage.setMessage(StringUtils.isNotBlank(currentQues.getName())?currentQues.getName():currentQues.getQuevoice());
										voiceResultList
												.add(new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
														null, currentQues.getQuevoice()));
									} else {
										retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
										retMessage.setMessage(currentQues.getName());
										retMessage.setExpmsg(currentQues.getName());
										voiceResultList
												.add(new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
														currentQues.getName(), null));
									}
								}
								if (2 == currentQues.getQuetype()) {
									aiUser.setBussend(true);
									queSurveyResultAnswer.setAnstatus("end");// 下个问题为结束
								} else if (3 == currentQues.getQuetype()) {
									aiUser.setBridge(true);
									aiUser.setTrans(currentQues.getTrans());
									queSurveyResultAnswer.setAnstatus("trans");// 下个问题为转接
								} else {
									queSurveyResultAnswer.setAnstatus("next");// 下一题
								}

							} else {
								retMessage = nextQue(aiUser,question,voiceResultList);
								isAddNext = true;
								nextQuestion = question;
								//下个问题
                                if (2 == question.getQuetype()) {
									//resultQuestion.setScore(resultQuestion.getScore() + question.getScore());
                                    // 一个问题为结束节点 结束通话hangup
                                    queSurveyResultAnswer.setAnstatus("end");// 下个问题为结束
                                } else if (3 == question.getQuetype()) {
                                    queSurveyResultAnswer.setAnstatus("trans");// 下个问题为转接
                                } else {
                                    queSurveyResultAnswer.setAnstatus("next");// 下一题
                                }
							}
							if (!StringUtils.isBlank(currentQues.getConfirmtype())
									&& currentQues.getConfirmtype().equals("voice")) {
								retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
								retMessage.setExpmsg(retMessage.getExpmsg() + "," + currentQues.getConfirmvoice());
								String text = currentQues.getConfirmword().replaceAll("\\{text\\}",
										asrResult.getMessage());
								retMessage.setMessage(retMessage.getMessage() + "," + (StringUtils.isNotBlank(text) ? (text + ",") : "") + currentQues.getConfirmvoice());
								voiceResultList.add(0,
										new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(), null,
												currentQues.getConfirmvoice()));
							} else {
								String text = currentQues.getConfirmword().replaceAll("\\{text\\}",
										asrResult.getMessage());
								retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
								retMessage.setMessage(retMessage.getMessage() + "," + (StringUtils.isNotBlank(text) ? (text + ",") : "") + text);
								retMessage.setExpmsg(retMessage.getExpmsg() + "," + (StringUtils.isNotBlank(text) ? (text + ",") : "") + text);
								voiceResultList.add(0, new VoiceResult(
										UKDataContext.MediaTypeEnum.TEXT.toString(), text, null));
							}
						}

						// 重复 或 错误语
						if (retMessage == null && !isInterrupt) {
							if (currentQues != null) {

								if (!StringUtils.isBlank(currentQues.getReplykeyword())
										&& matchKeyWord(currentQues.getReplykeyword(), asrResult.getMessage(), true,queSurveyResultAnswer)) {
									queSurveyResultAnswer.setAnswer(currentQues.getReplykeyword());
									queSurveyResultAnswer.setAnswertype(UKDataContext.AnswerType.REPEAT.toString());
									retMessage = newChatMsg(aiUser,null);


									if (!StringUtils.isBlank(currentQues.getReplyrepeat())
											&& currentQues.getReplyrepeat().matches("[0-9]")
											&& aiUser.getRetimes() >= Integer.parseInt(currentQues.getReplyrepeat())) {
										if ("trans".equals(currentQues.getReplyoperate())) {
											aiUser.setBridge(true);
											aiUser.setTrans(currentQues.getReplytrans());
											queSurveyResultAnswer.setAnstatus("trans");
										} else if("hangup".equals(currentQues.getReplyoperate())) {
											aiUser.setBussend(true);
											queSurveyResultAnswer.setAnstatus("end");
											if (!StringUtils.isBlank(currentQues.getReplytypeup())
													&& currentQues.getReplytypeup().equals("voice")) {
												if (!StringUtils.isBlank(currentQues.getReplyvoiceup())) {
													voiceResultList.add(
															new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
																	null, currentQues.getReplyvoiceup()));
													retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());

													String text = currentQues.getReplywordup().replaceAll("\\{text\\}",
															asrResult.getMessage());

													retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + (StringUtils.isNotBlank(text)?text:currentQues.getReplyvoiceup()));
													retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + currentQues.getReplyvoiceup());
												}
											} else {
												String text = currentQues.getReplywordup().replaceAll("\\{text\\}",
														asrResult.getMessage());
												voiceResultList.add(new VoiceResult(
														UKDataContext.MediaTypeEnum.TEXT.toString(), text, null));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());

												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + text);
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + text);

											}
										}else if(StringUtils.isNotBlank(currentQues.getReplyoperate())){
											//跳转 下一题
											nextQuestion = queSurveryQuesRes.findByOrgiAndId(currentQues.getOrgi(),currentQues.getReplyoperate());

											isAddNext = true;
											retMessage = nextQue(aiUser,nextQuestion,voiceResultList);
											queSurveyResultAnswer.setAnstatus("next");
										}

									} else {
										//未达到次数时 才播放重复提示语
										if (!StringUtils.isBlank(currentQues.getReplytype())
												&& currentQues.getReplytype().equals("voice")) {
											if (!StringUtils.isBlank(currentQues.getReplyvoice())) {
												voiceResultList.add(
														new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
																null, currentQues.getReplyvoice()));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());

												String text = currentQues.getReplyword().replaceAll("\\{text\\}",
														asrResult.getMessage());

												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + (StringUtils.isNotBlank(text)?text:currentQues.getReplyvoice()));
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + currentQues.getReplyvoice());

											}
										} else {
											String text = currentQues.getReplyword().replaceAll("\\{text\\}",
													asrResult.getMessage());
											voiceResultList.add(new VoiceResult(
													UKDataContext.MediaTypeEnum.TEXT.toString(), text, null));
											retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());

											retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + text);
											retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + text);

										}

										// retMessage.setMessage(currentQues.getReplyword() + "," +
										// currentQues.getName());
										aiUser.setRetimes(aiUser.getRetimes() + 1);
										resultQuestion.setRetimes(resultQuestion.getRetimes() + 1);
										queSurveyResultAnswer.setAnstatus("repeat");
									}
								} else {
									//问卷 回答错误语
									if(isError) {
										retMessage = newChatMsg(aiUser, null);
										String text = currentQues.getErrorword().replaceAll("\\{text\\}",
												asrResult.getMessage());


										queSurveyResultAnswer.setAnswer(currentQues.getErrorepeat());
										queSurveyResultAnswer.setAnswertype(UKDataContext.AnswerType.ERROR.toString());

										if (!StringUtils.isBlank(currentQues.getErrorepeat())
												&& currentQues.getErrorepeat().matches("[0-9]") && aiUser
												.getErrortimes() >= Integer.parseInt(currentQues.getErrorepeat())) {
											if ("trans".equals(currentQues.getErroroperate())) {
												aiUser.setBridge(true);
												aiUser.setTrans(currentQues.getErrortrans());
												queSurveyResultAnswer.setAnstatus("trans");
											} else if ("hangup".equals(currentQues.getErroroperate())) {
												aiUser.setBussend(true);
												queSurveyResultAnswer.setAnstatus("end");
												if (!StringUtils.isBlank(currentQues.getErrortypeup())
														&& currentQues.getErrortypeup().equals("voice")) {
													if (!StringUtils.isBlank(currentQues.getErrorvoiceup())) {
														voiceResultList.add(
																new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
																		null, currentQues.getErrorvoiceup()));

														String text1 = currentQues.getErrorwordup().replaceAll("\\{text\\}",
																asrResult.getMessage());

														retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + (StringUtils.isNotBlank(text1) ? text1 : currentQues.getErrorvoiceup()));
														retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + currentQues.getErrorvoiceup());

														retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
													}
												} else {
													String text1 = currentQues.getErrorwordup().replaceAll("\\{text\\}",
															asrResult.getMessage());
													voiceResultList.add(new VoiceResult(
															UKDataContext.MediaTypeEnum.TEXT.toString(), text1, null));
													retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());

													retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + text1);
													retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + text1);

												}
											} else if (StringUtils.isNotBlank(currentQues.getErroroperate())) {
												//跳转 下一题
												nextQuestion = queSurveryQuesRes.findByOrgiAndId(currentQues.getOrgi(), currentQues.getErroroperate());

												isAddNext = true;

												retMessage = nextQue(aiUser, nextQuestion, voiceResultList);
												queSurveyResultAnswer.setAnstatus("next");
											}
										} else {
											//未达到次数时 才播放错误提示语
											if (!StringUtils.isBlank(currentQues.getErrortype())
													&& currentQues.getErrortype().equals("voice")) {
												if (!StringUtils.isBlank(currentQues.getErrorvoice())) {
													voiceResultList.add(
															new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
																	null, currentQues.getErrorvoice()));
													retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());

													retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + (StringUtils.isNotBlank(text) ? text : currentQues.getErrorvoice()));
													retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + currentQues.getErrorvoice());

												}
											} else {

												voiceResultList.add(new VoiceResult(
														UKDataContext.MediaTypeEnum.TEXT.toString(), text, null));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + text);
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + text);
											}
											// retMessage.setMessage(currentQues.getErrorword());
											aiUser.setErrortimes(aiUser.getErrortimes() + 1);
											resultQuestion.setErrortimes(resultQuestion.getErrortimes() + 1);
											queSurveyResultAnswer.setAnstatus("error");
										}
									}
								}
							}
						}

						if (retMessage == null && !isrepeat && !isError && !isInterrupt) {//非重复节点 且没有设置回答错误 非打断
							//问卷则自动寻找下一题or话术结束
							if (UKDataContext.AiBussType.SALE.toString().equals(aiUser.getBusstype())) {
								//话术结束
								// 播放结束语音
								AiCallOutProcess process = salesPatterRes.findByIdAndOrgi(extention.getProid(), extention.getOrgi());
								retMessage = newChatMsg(aiUser,null);

								//话术结束语
								if (!StringUtils.isBlank(process.getEndtype())
										&& process.getEndtype().equals("voice")) {
									voiceResultList.add(
											new VoiceResult(
													UKDataContext.MediaTypeEnum.VOICE.toString(), null,
													process.getEndvoice()));
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
									retMessage.setExpmsg(process.getEndvoice());
									retMessage.setMessage(StringUtils.isNotBlank(process.getEndword())?process.getEndword():process.getEndvoice());
								} else {
									voiceResultList.add(
											new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
													process.getEndword(), null));
									retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
									retMessage.setMessage(process.getEndword());
									retMessage.setExpmsg(
											process.getEndword());
								}

								aiUser.setBussend(true);

								queSurveyResultAnswer.setAnstatus("end");// 结束

							} else {
								//问卷则自动寻找下一题
								/**
								 * 如果是最后一条，直接播放结束语音，否则进入到 下一条
								 */
								List<QueSurveyQuestion> quesList = loadQuestion(aiUser.getOrgi(), aiUser.getBussid());

								for (QueSurveyQuestion ques : quesList) {
									if (ques.getId().equals(aiUser.getDataid())) {
										if ((quesList.indexOf(ques) + 1) >= quesList.size()) {
											// 播放结束语音
											QueSurveyProcess process = queSurveryRes
													.findByIdAndOrgi(aiUser.getBussid(), aiUser.getOrgi());
											retMessage = newChatMsg(aiUser,null);

											if (!StringUtils.isBlank(ques.getConfirmtype())
													&& ques.getConfirmtype().equals("voice")) {
												voiceResultList.add(0,
														new VoiceResult(
																UKDataContext.MediaTypeEnum.VOICE.toString(), null,
																ques.getConfirmvoice()));
												retMessage.setExpmsg(ques.getConfirmvoice());
												String text = ques.getConfirmword().replaceAll("\\{text\\}",
														asrResult.getMessage());
												retMessage.setMessage(StringUtils.isNotBlank(text)?text:ques.getConfirmvoice());
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
											} else {
												String text = ques.getConfirmword().replaceAll("\\{text\\}",
														asrResult.getMessage());
												voiceResultList.add(0, new VoiceResult(
														UKDataContext.MediaTypeEnum.TEXT.toString(), text, null));
												retMessage.setMessage(text);
												retMessage.setExpmsg(text);
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
											}

											if (!StringUtils.isBlank(process.getEndtype())
													&& process.getEndtype().equals("voice")) {
												voiceResultList.add(
														new VoiceResult(
																UKDataContext.MediaTypeEnum.VOICE.toString(), null,
																process.getEndvoice()));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + (StringUtils.isNotBlank(process.getEndword())?process.getEndword():process.getEndvoice()));
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + process.getEndvoice());
											} else {
												voiceResultList.add(
														new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
																process.getEndword(), null));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + process.getEndword());
												retMessage.setExpmsg(retMessage.getMessage());
											}

											aiUser.setBussend(true);

											queSurveyResultAnswer.setAnstatus("end");// 结束

										} else {
											QueSurveyQuestion nextquestion = quesList.get(quesList.indexOf(ques) + 1);
											isAddNext = true;
											nextQuestion = nextquestion;
											aiUser.setDataid(nextquestion.getId());
											//设置是否允许打断 最大说话时长
											aiUser.setInterrupt(nextquestion.isInterrupt());
											aiUser.setInterrupttime(nextquestion.getInterrupttime() * 1000);
											aiUser.setMaxspreak(nextquestion.getMaxspreak() * 1000);
											//设置 等待超时时长
											aiUser.setLastreplytime(nextquestion.getOvertime() * 1000);
											retMessage = newChatMsg(aiUser,null);

											if (!StringUtils.isBlank(ques.getConfirmtype())
													&& ques.getConfirmtype().equals("voice")) {
												voiceResultList.add(new VoiceResult(
														UKDataContext.MediaTypeEnum.VOICE.toString(), null,
														ques.getConfirmvoice()));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + (StringUtils.isNotBlank(ques.getConfirmword())?ques.getConfirmword():ques.getConfirmvoice()));
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + ques.getConfirmvoice());
											} else {
												String text = ques.getConfirmword().replaceAll("\\{text\\}",
														asrResult.getMessage());
												voiceResultList.add(new VoiceResult(
														UKDataContext.MediaTypeEnum.TEXT.toString(), text, null));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + ques.getConfirmword());
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + ques.getConfirmword());
											}
											//下一个问题欢迎语
											if (!StringUtils.isBlank(nextquestion.getWvtype())
													&& nextquestion.getWvtype().equals("voice")) {
												voiceResultList.add(new VoiceResult(
														UKDataContext.MediaTypeEnum.VOICE.toString(), null,
														nextquestion.getQuevoice()));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + (StringUtils.isNotBlank(nextquestion.getName())?nextquestion.getName():nextquestion.getQuevoice()));
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + nextquestion.getQuevoice());
											} else {
												voiceResultList.add(
														new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
																nextquestion.getName(), null));
												retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
												retMessage.setMessage((StringUtils.isNotBlank(retMessage.getMessage()) ? (retMessage.getMessage() + ",") : "") + nextquestion.getName());
												retMessage.setExpmsg((StringUtils.isNotBlank(retMessage.getExpmsg()) ? (retMessage.getExpmsg() + ",") : "") + nextquestion.getName());
											}
											queSurveyResultAnswer.setAnstatus("next");// 下一题
											if (2 == nextquestion.getQuetype()) {
												// 一个问题为结束节点 结束通话hangup
												aiUser.setBussend(true);
												queSurveyResultAnswer.setAnstatus("end");
											} else if (3 == nextquestion.getQuetype()) {
												aiUser.setBridge(true);
												aiUser.setTrans(nextquestion.getTrans());
												queSurveyResultAnswer.setAnstatus("trans");// 下个问题为转接
											}

										}
										break;
									}
								}
							}
						}
						if(ans != null){
							queSurveyResultAnswer.setAnswer(ans != null ? ans.getAnswer() : data.getMessage());
							if("0".equals(ans.getAnstype())){
								if(ans.isInterrupt()){
									queSurveyResultAnswer.setAnswertype(UKDataContext.AnswerType.ANSWER_INTERRUPT.toString());
								}else{
									queSurveyResultAnswer.setAnswertype(UKDataContext.AnswerType.ANSWER.toString());
								}
							}else if("1".equals(ans.getAnstype())){
								if(ans.isInterrupt()){
									queSurveyResultAnswer.setAnswertype(UKDataContext.AnswerType.ANSWER_PUBLIC_INTERRUPT.toString());
								}else{
									queSurveyResultAnswer.setAnswertype(UKDataContext.AnswerType.ANSWER_PUBLIC.toString());
								}
							}
						}
						if (aiUser.isBussend()|| aiUser.isBridge()) {
							resultQuestion.setEndtime(new Date());
						}
						//记录问题结果
						if (isadd) {
							resultQuestion = queSurveyResultQuestionRes.save(resultQuestion);
							aiUser.getQuestionList().add(resultQuestion);
						}
						if(isAddNext && nextQuestion != null){
							QueSurveyResultQuestion resultQuestion2 = null;
							//问题不存在 或者 问题已经换了
							if (resultQuestion2 == null) {
								//new 一个
								resultQuestion2 = new QueSurveyResultQuestion();
								resultQuestion2.setEventid(aiUser.getUsername());
								resultQuestion2.setProcessid(aiUser.getBussid());
								resultQuestion2.setQuestionid(aiUser.getDataid());
								resultQuestion2.setOrgi(aiUser.getOrgi());
								resultQuestion2.setCreatetime(new Date());
								resultQuestion2.setScore(nextQuestion.getScore());
							}
							//记录问题结果
							if (aiUser.isBussend() || aiUser.isBridge()) {
								resultQuestion2.setEndtime(new Date());
							}
							resultQuestion2 = queSurveyResultQuestionRes.save(resultQuestion2);
							aiUser.getQuestionList().add(resultQuestion2);
						}

						//记录匹配的答案
						queSurveyResultAnswer.setResultquesid(resultQuestion.getId());
						queSurveyResultAnswer.setProcessid(currentQues.getProcessid());
						queSurveyResultAnswer.setQuestionid(currentQues.getId());
						queSurveyResultAnswer.setAnswerid(ans != null ? ans.getId() : null);

						queSurveyResultAnswer.setAnswermsg(data.getMessage());
						queSurveyResultAnswer.setAnswerexpmsg(data.getExpmsg());

						queSurveyResultAnswer.setAnswerscore(ans != null ? ans.getAnswerscore() : 0);
						queSurveyResultAnswer.setCorrect(ans != null ? ans.getCorrect() : "0");

						queSurveyResultAnswer.setQuetype(currentQues.getQuetype());
						queSurveyResultAnswer.setOrgi(aiUser.getOrgi());
						queSurveyResultAnswer.setCreater(aiUser.getUserid());
						queSurveyResultAnswer.setCreatetime(new Date());

						if(StringUtils.isBlank(queSurveyResultAnswer.getAnswertype())){
							queSurveyResultAnswer.setAnswertype(UKDataContext.AnswerType.UNMATCH.toString());
						}
						queSurveyResultAnswer.setStatuseventid(robotParam.getCdrid());
						queSurveyResultAnswerRes.save(queSurveyResultAnswer);
						/*}*/
						queSurveyResult.setAnswertimes(ansnum);// 回答次数
						queSurveyResultRes.save(queSurveyResult);

					}

				/**
				 * 回复消息
				 */
				if (retMessage != null && !StringUtils.isBlank(retMessage.getMessage())) {
					retMessage.setCreatedate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					MessageUtils.createAiMessage(retMessage, retMessage.getAppid(),
							retMessage.getChannel(), UKDataContext.CallTypeEnum.OUT.toString(),
							UKDataContext.AiItemType.AIREPLY.toString(),
							UKDataContext.MediaTypeEnum.TEXT.toString(), retMessage.getUserid());

					if (voiceResultList.size() > 0) {
						List<String> voices = new ArrayList<>();
						for (VoiceResult voiceResult : voiceResultList) {
							if (UKDataContext.MediaTypeEnum.TEXT.toString().equals(voiceResult.getVoicetype())) {
								String tts = null;
								if (!StringUtils.isBlank(voiceResult.getTts())) {
									tts = Jsoup.parse(voiceResult.getTts()).text();
									if (tts.length() > 300) {
										tts = tts.substring(0, 300);
									}
									voices.add(processMessage(tts, dataBean));
								}
							} else {
								voices.add(processVoiceURL(voiceResult.getVoice(),extention.getOrgi()));
							}
						}
						if (aiUser.isBussend()) {
							robotReturnParam = hangUpList(voices, aiUser);
						} else if (aiUser.isBridge()) {
							robotReturnParam = transfer(aiUser.getTrans(), voices, aiUser);
						} else {
							robotReturnParam = defaultplayback(voices, aiUser);
						}
					}
					CacheHelper.getOnlineUserCacheBean().put(aiUser.getSessionid(), aiUser, UKDataContext.SYSTEM_ORGI);
				}
			}
		} else {
			//robotReturnParam = hangUp();
		}
		if (robotReturnParam == null) {
			robotReturnParam = noop(true,aiUser);
		}
		return robotReturnParam;
	}


	/**
	 * 智能机器人asr结果处理
	 * @param robotParam
	 * @param callid
	 * @param extention
	 * @param callerid
	 * @param dataBean
	 * @return
	 * @throws JSONException
	 */
	@SuppressWarnings("unused")
	public RobotReturnParam aiasrProcess(RobotParam robotParam, String callid, Extention extention, String callerid,
									   UKDataBean dataBean) throws JSONException {
		AiUser aiUser = (AiUser) CacheHelper.getOnlineUserCacheBean().getCacheObject(callid, extention.getOrgi());
		RobotReturnParam robotReturnParam = null;
		if (aiUser != null && aiUser.isBussend() == false) {
			ChatMessage data = newChatMsg(aiUser,null);
			//TODO 返回 客户说话时长
			/*AsrResult asrResult = UKTools.parseAsrResult(robotParam.getCdrid(), robotParam.getText(),
					0);*/
			AsrResult asrResult = new AsrResult(robotParam.getCdrid(), robotParam.getText(),"0");

			if(StringUtils.isNotBlank(robotParam.getWavfile())){
				asrResult.setRecordpath(robotParam.getWavfile());
			}
			data.setAiid(extention.getAiid());
			if (asrResult != null && !StringUtils.isBlank(asrResult.getMessage())) {
				asrResult.setMessage(asrResult.getMessage().replaceAll("[\\p{P}+~$`^=|<>～｀＄＾＋＝｜＜＞￥×]", ""));
				if (asrResult.getMessage().endsWith("。")) {
					data.setMessage(asrResult.getMessage().substring(0, asrResult.getMessage().length() - 1));
				} else {
					data.setMessage(asrResult.getMessage());
				}
				data.setDuration((int) Math.ceil(asrResult.getSpeakms() / 1000f));
				data.setExpmsg(asrResult.getMessage());
				List<VoiceResult> voiceResultList = new ArrayList<VoiceResult>();

				//TODO 确认录音地址
				if (!StringUtil.isBlank(data.getMessage())) {
					data.setUrl("/apps/resource/asr/" + asrResult.getRecordpath());
				}
				data.setMediaid(robotParam.getCdrid());

				/**
				 * 输入消息
				 */
				MessageUtils.createAiMessage(data, data.getAppid(), UKDataContext.ChannelTypeEnum.PHONE.toString(),
						UKDataContext.CallTypeEnum.IN.toString(), UKDataContext.AiItemType.USERINPUT.toString(),
						UKDataContext.MediaTypeEnum.TEXT.toString(), data.getUserid());
				/**
				 * 使用 ASR识别结果作为消息内容
				 */
				data.setMessage(data.getExpmsg());

				ChatMessage retMessage = null;
				if (!StringUtils.isBlank(aiUser.getAitype())
						&& aiUser.getAitype().equals(UKDataContext.AiType.BUSINESSAI.toString())) {


				} else {
					//智能机器人 分开接口
					data.setMediaid("");
					retMessage = aiMessageProcesser.chat(data);
					aiUser.setRetimes(0);
				}
				/**
				 * 回复消息
				 */
				if (retMessage != null && !StringUtils.isBlank(retMessage.getMessage())) {
					retMessage.setCreatedate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					MessageUtils.createAiMessage(retMessage, retMessage.getAppid(),
							retMessage.getChannel(), UKDataContext.CallTypeEnum.OUT.toString(),
							UKDataContext.AiItemType.AIREPLY.toString(),
							UKDataContext.MediaTypeEnum.TEXT.toString(), retMessage.getUserid());

					//智能机器人
					String retText = retMessage != null && !StringUtils.isBlank(retMessage.getMessage())
							? retMessage.getMessage()
							: extention.getTipmessage();
					if (!StringUtils.isBlank(retText)) {
						List<String> voices = new ArrayList<>();
						if (UKDataContext.MediaTypeEnum.TEXT.toString().equals(retMessage.getMsgtype())) {
							String tts = null;
							if (!StringUtils.isBlank(retMessage.getMessage())) {
								tts = Jsoup.parse(retMessage.getMessage()).text();
								if (tts.length() > 300) {
									tts = tts.substring(0, 300);
								}
								voices.add(processMessage(tts, dataBean));
							}
						} else {
							voices.add(retMessage.getMessage());
						}
						//外部机器人挂断
						if (UKDataContext.MediaTypeEnum.HUNGUP.toString().equalsIgnoreCase(retMessage.getBustype())) {
							robotReturnParam = hangUpList(voices, aiUser);
						} else if (UKDataContext.MediaTypeEnum.TRANS.toString().equalsIgnoreCase(retMessage.getBustype())) {
							//转接
							aiUser.setTrans(retMessage.getCode());
							robotReturnParam = transfer(aiUser.getTrans(), voices, aiUser);
						} else {
							robotReturnParam = defaultplayback(voices, aiUser);
						}
					}
					CacheHelper.getOnlineUserCacheBean().put(aiUser.getSessionid(), aiUser, UKDataContext.SYSTEM_ORGI);
				}
			}
		} else {
			//map = hangUp();
		}
		if (robotReturnParam == null) {
			robotReturnParam = noop(true,aiUser);
		}
		return robotReturnParam;
	}

	/**
	 * 判断结果是否命中关键词
	 *
	 * @param configKeyWord
	 * @param keyword
	 * @return
	 */
	private boolean matchKeyWord(String configKeyWord, String keyword, boolean include) {
		return matchKeyWord(configKeyWord,keyword,include,null);
	}


	/**
	 * 判断结果是否命中关键词
	 *
	 * @param configKeyWord
	 * @param keyword
	 * @return
	 */
	private boolean matchKeyWord(String configKeyWord, String keyword, boolean include,QueSurveyResultAnswer answer) {
		boolean match = false;
		if (!StringUtils.isBlank(keyword)) {
			keyword = keyword.trim();
			if (!StringUtils.isBlank(configKeyWord)) {
				String[] keywords = configKeyWord.split("[,，]");
				for (String kw : keywords) {
					//kw = kw.replaceAll("\\*", "[\\\\S\\\\s]*?");
					kw = kw.trim();
					if (!StringUtils.isBlank(kw)) {
						String pinyin = PinYinTools.getInstance().getSelling(keyword);
						String firstPinYin = PinYinTools.getInstance().getFirstPinYinAll(keyword);

						if (keyword.matches(kw) || (!StringUtils.isBlank(pinyin) && pinyin.toLowerCase().matches(kw))
								|| (!StringUtils.isBlank(firstPinYin) && firstPinYin.matches(kw))) {
							match = true;
							if(answer != null){
								answer.setMatchtype("matches");
								answer.setMatchkey(kw);
							}
							break;
						}
						if (include && keyword.indexOf(kw) >= 0) {
							match = true;
							if(answer != null){
								answer.setMatchtype("indexof");
								answer.setMatchkey(kw);
							}
							break;
						}
					}
				}
			}
		}
		return match;
	}


	/**
	 * 放音
	 * @param message
	 * @param aiuser
	 * @return
	 */
	public RobotReturnParam fangyinList(List<String> message, AiUser aiuser) {

		RobotReturnParam robotReturnParam = new RobotReturnParam(aiuser);

		List<String> playbackMusic = new ArrayList<String>();
		if (message.size() > 0) {
			for (String s : message) {
				//TODO ？
				if (StringUtils.isNotBlank(s.replaceAll("[\\pP\\p{Punct}]", " "))) {
					playbackMusic.add(s);
				}
			}
		}
		robotReturnParam.setPlayvoice(StringUtils.join(playbackMusic,";"));
		//如果没录音 没匹配到 "param2":"1",    扩展参数2,="-9"表示识别出来的文本没匹配到关键字,暂停的语音继续播放
		if (playbackMusic.size() == 0) {
			robotReturnParam = noop(true,aiuser);
		}

		return robotReturnParam;
	}

	/**
	 * 根据流程，组装对应的放音json
	 *
	 * @param flow 放音音频
	 * @author cxy
	 * @version 2018-04-15
	 */
	/*public RobotReturnParam playback(List<String> music, AiUser aiUser) {
		RobotReturnParam robotReturnParam = new RobotReturnParam();

		if (aiUser.isInterrupt()) {
			flowdata.put("interrupt", "1");
		}

		*//*Map<String, Object> map = new HashMap<String, Object>();
		map.put("action", "playback");
		// 缓存中取出这步的业务名称
		Map<String, String> flowdata = processFlowData("default");
		if (aiUser.isInterrupt()) {
			flowdata.put("interrupt", "1");
		}
		map.put("flowdata", flowdata);
		Map<String, Object> params = new HashMap<String, Object>();*//*
		List<String> playbackMusic = new ArrayList<String>();
		if (music.size() > 0) {
			for (String s : music) {
				if (StringUtils.isNotBlank(s.replaceAll("[\\pP\\p{Punct}]", " "))) {
					playbackMusic.add(s);
				}
			}
		}
		params.put("max_speak_ms", aiUser.getMaxspreak());

		params.put("prompt", playbackMusic);
		params.put("wait", aiUser!=null && aiUser.getLastreplytime() > 0 ?aiUser.getLastreplytime() : waittime);
		params.put("retry", 0);
		params.put("allow_interrupt", aiUser.isInterrupt() ? aiUser.getInterrupttime() : -1);//0允许，-1不允许，大于0 播放多久才允许自动打断
		params.put("block_asr", aiUser.isInterrupt() ? aiUser.getInterrupttime() : -1);

		//设置了语种/方言  就读取对应的配置文件路径
		if (aiUser != null && StringUtils.isNotBlank(aiUser.getLanguage()) && StringUtils.isNotBlank(aiUser.getLanguagepath())) {
			params.put("tts_configure_filename", aiUser.getLanguagepath());
		}

		map.put("params", params);
		if (playbackMusic.size() == 0) {
			map = noop(null);
		}
		return map;
	}*/

	/**
	 * 流程中放音
	 * @param music
	 * @param aiUser
	 * @return
	 */
	public RobotReturnParam defaultplayback(List<String> music, AiUser aiUser) {
		RobotReturnParam robotReturnParam = new RobotReturnParam(aiUser);

		List<String> playbackMusic = new ArrayList<String>();

		if (music.size() > 0) {
			for (String s : music) {
				if (StringUtils.isNotBlank(s.replaceAll("[\\pP\\p{Punct}]", " "))) {
					playbackMusic.add(s);
				}
			}
		}
		//超时时间
		robotReturnParam.setAsrtimeout(aiUser!=null && aiUser.getLastreplytime() > 0 ?aiUser.getLastreplytime()/1000+"" : waittime/1000 + "");

		//是否允许打断 允许打断开始时长
		if(aiUser.isInterrupt() && aiUser.getInterrupttime() > 0){
			robotReturnParam.setAsrtimeout(robotReturnParam.getAsrtimeout() + "|" + aiUser.getInterrupttime()/1000);
		}
		if(aiUser.isInterrupt()){
			robotReturnParam.setAsrvoice(StringUtils.join(playbackMusic,";"));
		}else{
			robotReturnParam.setPlayvoice(StringUtils.join(playbackMusic,";"));
			robotReturnParam.setAsrvoice("m00.wav");
		}

		//如果没录音 没匹配到 "param2":"1",    扩展参数2,="-9"表示识别出来的文本没匹配到关键字,暂停的语音继续播放
		if (playbackMusic.size() == 0) {
			robotReturnParam = noop(true,aiUser);
		}


		return robotReturnParam;
	}

	/**
	 * 放音后挂断
	 * @return
	 */
	public RobotReturnParam hangUp() {
		RobotReturnParam robotReturnParam = new RobotReturnParam();
		// <0 为挂机
		robotReturnParam.setQueueid("-1");
		return robotReturnParam;
	}

	/**
	 * 未匹配中结果 ， 继续播放录音
	 * @return
	 */
	/*public RobotReturnParam consolePlayback() {
		RobotReturnParam robotReturnParam = new RobotReturnParam();
		robotReturnParam.setParam2("-9");

		return robotReturnParam;
	}*/

	/**
	 * 挂断
	 * @param voice
	 * @param aiuser
	 * @return
	 */
	public RobotReturnParam hangUpList(List<String> voice, AiUser aiuser) {

		RobotReturnParam robotReturnParam = new RobotReturnParam(aiuser);
		// <0 为挂机
		robotReturnParam.setQueueid("-1");

		List<String> playbackMusic = new ArrayList<>();
		if (voice.size() > 0) {
			for (String s : voice) {
				if (StringUtils.isNotBlank(s)) {
					playbackMusic.add(s);
				}
			}
		}else{
			playbackMusic.add("m00.wav");
		}
		//延迟挂机
		if(aiuser.getDelaytime() > 0){
			robotReturnParam.setAsrtimeout((aiuser.getDelaytime()/1000) + "");
		}else {
			robotReturnParam.setAsrtimeout("0");
		}

		robotReturnParam.setPlayvoice(StringUtils.join(playbackMusic,";"));
		return robotReturnParam;

	}


	/**
	 * 转接 transfer 形式
	 *
	 * @param number
	 * @param voice
	 * @return
	 */
	public RobotReturnParam transfer(String number, List<String> voice, AiUser aiuser) {

		RobotReturnParam robotReturnParam = new RobotReturnParam(aiuser);

		// >0 转接号码
		robotReturnParam.setQueueid(number);
		List<String> playbackMusic = new ArrayList<>();
		if (voice.size() > 0) {

			for (String s : voice) {
				if (StringUtils.isNotBlank(s.replaceAll("[\\pP\\p{Punct}]", " "))) {
					playbackMusic.add(s);
				}
			}
		}else{
			playbackMusic.add("m00.wav");
		}
		robotReturnParam.setAsrtimeout("0");
		
		robotReturnParam.setPlayvoice(StringUtils.join(playbackMusic,";"));
		return robotReturnParam;

	}

	/**
	 * 挂断后操作
	 *
	 * @param aiUser
	 * @param extention
	 */
	private void afterleave(AiUser aiUser, Extention extention, UKDataBean dataBean,RobotParam robotParam) {
		QueSurveyResult queSurveyResult = queSurveyResultRes.findByIdAndOrgi(aiUser.getQueresultid(),
				aiUser.getOrgi());

		AiCallOutProcess process = null;
		// 话术or问卷
		if (extention.getBustype().equals("sale")) {
			process = salesPatterRes.findByIdAndOrgi(extention.getProid(), extention.getOrgi());
		} else {
			process = queSurveryRes.findByIdAndOrgi(extention.getQueid(), extention.getOrgi());
		}
		int sumscore = 0;
		// 问卷结果主表
		if (queSurveyResult != null) {
			int focustimes = 0;//关注点次数
			LinkedList<QueSurveyResultQuestion> list = aiUser.getQuestionList();
			if (list.size() > 0) {
				for (Iterator<QueSurveyResultQuestion> iter = list.iterator(); iter.hasNext(); ) {
					List<QueSurveyResultPoint> resultPointList = new ArrayList<>();
					QueSurveyResultQuestion q = iter.next();
					if (q.getEndtime() != null && q.getCreatetime() != null) {
						q.setProcesstime(new Long(q.getEndtime().getTime() - q.getCreatetime().getTime()).intValue());
					}
					q.setStatuseventid(robotParam.getCdrid());
					int qsumscore = 0;
					int focustimesq = 0;
					if ("1".equals(process.getScore())) {
						//统计每个问题初始分
						sumscore = sumscore + q.getScore();
						List<SalesPatterPoint> pointList = salesPatterPointRes.findByQuestionidAndOrgi(q.getQuestionid(), aiUser.getOrgi());
						if (pointList != null && pointList.size() > 0) {
							for (SalesPatterPoint point : pointList) {
								if ("0".equals(point.getPointtype())) {
									//关键字匹配
									String[] answers = q.getAnswer().split("[,\\\\|，]");
									for (String answerword : answers) {
										boolean match = matchKeyWord(point.getFocusword(), answerword, false);
										if (match) {
											qsumscore = qsumscore + point.getScore();
											focustimes++;
											focustimesq++;
											//记录匹配关注点
											QueSurveyResultPoint qpoint = new QueSurveyResultPoint();
											qpoint.setEventid(queSurveyResult.getEventid());
											qpoint.setResultid(queSurveyResult.getId());
											qpoint.setProcessid(q.getProcessid());
											qpoint.setPointid(point.getId());
											qpoint.setQuestionid(q.getQuestionid());
											qpoint.setOrgi(q.getOrgi());
											qpoint.setCreater(q.getCreater());
											qpoint.setCreatetime(new Date());
											qpoint.setPointtype(point.getPointtype());
											qpoint.setFocusword(point.getFocusword());
											qpoint.setMaxcalltime(point.getMaxcalltime());
											qpoint.setMincalltime(point.getMincalltime());
											qpoint.setScore(point.getScore());
											qpoint.setAnswer(answerword);
											qpoint.setPointname(point.getName());
											qpoint.setStatuseventid(q.getStatuseventid());
											resultPointList.add(qpoint);
										}
									}
								} else {
									//判断通话时长
									if (point.getMincalltime() != null && point.getMaxcalltime() != null) {
										if (q.getProcesstime() >= point.getMincalltime() * 1000 && q.getProcesstime() <= point.getMaxcalltime() * 1000) {
											qsumscore = qsumscore + point.getScore();
											focustimes++;
											focustimesq++;
											//记录匹配关注点
											QueSurveyResultPoint qpoint = new QueSurveyResultPoint();
											qpoint.setEventid(queSurveyResult.getEventid());
											qpoint.setResultid(queSurveyResult.getId());
											qpoint.setProcessid(q.getProcessid());
											qpoint.setPointid(point.getId());
											qpoint.setQuestionid(q.getQuestionid());
											qpoint.setOrgi(q.getOrgi());
											qpoint.setCreater(q.getCreater());
											qpoint.setCreatetime(new Date());
											qpoint.setPointtype(point.getPointtype());
											qpoint.setFocusword(point.getFocusword());
											qpoint.setMaxcalltime(point.getMaxcalltime());
											qpoint.setMincalltime(point.getMincalltime());
											qpoint.setScore(point.getScore());
											qpoint.setAnswertime(q.getProcesstime());
											qpoint.setPointname(point.getName());
											qpoint.setStatuseventid(q.getStatuseventid());
											resultPointList.add(qpoint);
										}
									}
								}
							}
						}
						//统计每个问题关注点得分
						sumscore = sumscore + qsumscore;
						q.setSumscore(qsumscore);
						q.setFocustimes(focustimesq);
					}
					q.setProcessid(aiUser.getQueresultid());
					q.setNameid(queSurveyResult.getNameid());
					q.setResultid(queSurveyResult.getId());
					queSurveyResultQuestionRes.save(q);
					if (resultPointList.size() > 0) {
						for (QueSurveyResultPoint r : resultPointList) {
							r.setResultqueid(q.getId());
							r.setNameid(q.getNameid());
						}
						queSurveyResultPointRes.save(resultPointList);
					}
				}
			}
			if ("1".equals(process.getScore())) {
				List<QueSurveyResultAnswer> queSurveyResultAnswerList = queSurveyResultAnswerRes.findByResultidAndProcessidAndOrgi(queSurveyResult.getId(), process.getId(),
						aiUser.getOrgi());
				//统计每个问题 答案分数
				if (queSurveyResultAnswerList.size() > 0) {
					for (QueSurveyResultAnswer a : queSurveyResultAnswerList) {
						sumscore = sumscore + a.getAnswerscore();
					}
				}
			}
			String level = "";
			//计算评级
			if ("1".equals(process.getScore())) {
				List<SalesPatterLevel> levelList = salesPatterLevelRepository.findByProcessidAndOrgi(process.getId(), aiUser.getOrgi());
				for (SalesPatterLevel sptl : levelList) {
					if (sptl.getMinscore() != null && sptl.getMaxscore() != null) {
						if (sumscore >= sptl.getMinscore() && sumscore <= sptl.getMaxscore()) {
							level = sptl.getName();
						}
					}
				}
			}
			if (dataBean != null) {
				dataBean = SearchTools.get(StringUtils.isNotBlank(dataBean.getType()) ? dataBean.getType() : (dataBean.getTable() != null ? dataBean.getTable().getTablename() : ""), (String) dataBean.getValues().get("id"));
				if (dataBean != null) {
					//只更新以下字段
					UKDataBean updateBean = new UKDataBean();
					updateBean.setType(dataBean.getType());
					updateBean.setId(dataBean.getId());
					Map<String, Object> map = new HashMap<>();
					map.put("id", StringUtils.isNotBlank(dataBean.getId()) ? dataBean.getId() : dataBean.getValues().get("id"));
					map.put("levelscore", sumscore);
					map.put("focustimes", focustimes);
					map.put("level", level);
					updateBean.setValues(map);
					SearchTools.updateAndRefresh(updateBean, true);

				}
			}

			StatusEvent statusEvent = statusEventRes.findByIdAndOrgi(robotParam.getCdrid(), extention.getOrgi());

			if(statusEvent != null){
				StatusEventRobot statusEventRobot = new StatusEventRobot();
				statusEventRobot.setId(statusEvent.getId());
				statusEventRobot.setLevel(level);
				statusEventRobot.setLevelscore(sumscore);
				statusEventRobot.setFocustimes(focustimes);
				statusEventRobot.setProcessid(process.getId());
				statusEventRobotRepository.save(statusEventRobot);
			}
			queSurveyResult.setSumscore(Integer.toString(sumscore));
			queSurveyResult.setTimeouttimes(aiUser.getTimeoutnums());
			queSurveyResult.setErrortimes(aiUser.getErrortimes());
			queSurveyResult.setRetimes(aiUser.getRetimes());
			queSurveyResult.setEndtime(new Date());
			queSurveyResult.setStatuseventid(robotParam.getCdrid());
			queSurveyResult.setProcesstime(
					new Long(new Date().getTime() - queSurveyResult.getCreatetime().getTime())
							.intValue());
			queSurveyResult.setFocustimes(focustimes);
			queSurveyResult.setLevel(level);
			queSurveyResultRes.save(queSurveyResult);
		}
	}

	/**
	 * 跳转下一题
	 * @param aiUser
	 * @param nextQuestion
	 * @param voiceResultList
	 */
	private ChatMessage nextQue(AiUser aiUser,QueSurveyQuestion nextQuestion,List<VoiceResult> voiceResultList){
		//下个问题
		aiUser.setDataid(nextQuestion.getId());
		//设置是否允许打断 最大说话时长
		aiUser.setInterrupt(nextQuestion.isInterrupt());
		aiUser.setInterrupttime(nextQuestion.getInterrupttime() * 1000);
		aiUser.setMaxspreak(nextQuestion.getMaxspreak() * 1000);
		//设置 等待超时时长
		aiUser.setLastreplytime(nextQuestion.getOvertime() * 1000);
		aiUser.setBridge(false);

		ChatMessage retMessage = newChatMsg(aiUser,nextQuestion);
		if (!StringUtils.isBlank(nextQuestion.getWvtype())
				&& nextQuestion.getWvtype().equals("voice")) {
			retMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
			retMessage.setMessage(nextQuestion.getQuevoice());

			retMessage.setMessage((StringUtils.isNotBlank(nextQuestion.getName()) ? nextQuestion.getName() : nextQuestion.getQuevoice()));
			retMessage.setExpmsg(nextQuestion.getQuevoice());

			voiceResultList
					.add(new VoiceResult(UKDataContext.MediaTypeEnum.VOICE.toString(),
							null, nextQuestion.getQuevoice()));
		} else {
			retMessage.setMsgtype(UKDataContext.MediaTypeEnum.TEXT.toString());
			retMessage.setMessage(nextQuestion.getName());
			retMessage.setExpmsg(nextQuestion.getName());
			voiceResultList
					.add(new VoiceResult(UKDataContext.MediaTypeEnum.TEXT.toString(),
							nextQuestion.getName(), null));
		}
		if (2 == nextQuestion.getQuetype()) {
			// 一个问题为结束节点 结束通话hangup
			aiUser.setBussend(true);
		} else if (3 == nextQuestion.getQuetype()) {
			aiUser.setBridge(true);
			aiUser.setTrans(nextQuestion.getTrans());
		}
		return retMessage;
	}

	private ChatMessage newChatMsg(AiUser aiUser,QueSurveyQuestion nextQuestion){
		ChatMessage retMessage = new ChatMessage();
		retMessage.setMessage(nextQuestion != null ? nextQuestion.getName():"");
		retMessage.setAppid(aiUser.getAppid());
		retMessage.setUserid(aiUser.getUserid());
		retMessage.setUsername("小E");
		retMessage.setAichat(true);
		retMessage.setChannel(aiUser.getChannel());
		retMessage.setType(UKDataContext.MessageTypeEnum.MESSAGE.toString());
		retMessage.setContextid(aiUser.getContextid());
		retMessage.setOrgi(aiUser.getOrgi());
		retMessage.setAgentserviceid(aiUser.getAgentserviceid());
		return retMessage;
	}

	/**
	 * 加载答案（需要缓存）
	 * @param questionid 问题id
	 * @param orgi
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<QueSurveyAnswer> loadAnswer(String questionid ,String orgi){
		List<QueSurveyAnswer> ansList = (List<QueSurveyAnswer>) CacheHelper.getSystemCacheBean().getCacheObject(questionid + UKDataContext.SYSTEM_CACHE_SPT_ANSWER_KEY, orgi) ;
		if(ansList == null || ansList.size() == 0){
			ansList = queSurveryAnswerRes.findByOrgiAndQuestionidAndAnstypeOrderBySortindexAsc(orgi,
					questionid, "0");
			CacheHelper.getSystemCacheBean().put(questionid + UKDataContext.SYSTEM_CACHE_SPT_ANSWER_KEY,ansList, orgi) ;
		}
		return ansList ;
	}

	/**
	 * 加载公共答案，需要缓存
	 * @param processid 话术id
	 * @param orgi
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<QueSurveyAnswer> loadPubAnswer(String processid ,String orgi,Boolean interrupt){
		List<QueSurveyAnswer> publicAnsList = (List<QueSurveyAnswer>) CacheHelper.getSystemCacheBean().getCacheObject(processid + UKDataContext.SYSTEM_CACHE_SPT_PUB_ANSWER_KEY, orgi) ;
		if(publicAnsList == null || publicAnsList.size() == 0){
			publicAnsList = queSurveryAnswerRes.findByOrgiAndProcessidAndAnstypeOrderBySortindexAsc(orgi,
					processid, "1");
			CacheHelper.getSystemCacheBean().put(processid + UKDataContext.SYSTEM_CACHE_SPT_PUB_ANSWER_KEY,publicAnsList, orgi) ;
		}
		List<QueSurveyAnswer> ansList = new ArrayList<>();
		if(interrupt != null && publicAnsList != null && publicAnsList.size() > 0){
			for(QueSurveyAnswer answer : publicAnsList ){
				if(interrupt == answer.isInterrupt()){
					ansList.add(answer);
				}
			}
		}else{
			return publicAnsList;
		}
		return ansList ;
	}

	/**
	 * 加载问题，需要缓存
	 * @param orgi
	 * @param processid 话术id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<QueSurveyQuestion> loadQuestion(String orgi , String processid ){
		List<QueSurveyQuestion> quesList = (List<QueSurveyQuestion>) CacheHelper.getSystemCacheBean().getCacheObject(processid + UKDataContext.SYSTEM_CACHE_SPT_QUES_KEY, orgi) ;
		if(quesList == null || quesList.size() == 0){
			quesList = queSurveryQuesRes.findByOrgiAndProcessidOrderBySortindexAsc(orgi, processid);
			CacheHelper.getSystemCacheBean().put(processid + UKDataContext.SYSTEM_CACHE_SPT_QUES_KEY,quesList, orgi) ;
		}

		return quesList ;
	}
}
